package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 黄晏凯
 */
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) throws Exception {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (null == wmNews) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 状态为1，才执行审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从内容中提取纯文本内容和图片
            Map<String, Object> data = handleTextAndImages(wmNews);
            //自管理的敏感词过滤
            boolean status = handleSensitiveScan(data.get("text").toString(), wmNews);
            if (!status) {
                return;
            }
            //2.审核文本内容  阿里云接口
            status = handleTextScan(data.get("text").toString(), wmNews);
            if (!status) {
                return;
            }
            //3.审核图片  阿里云接口
            status = handleImageScan((List<String>) data.get("images"), wmNews);
            if (!status) {
                return;
            }
            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new CustomException(AppHttpCodeEnum.DATA_SYNC_FAIL);
            }
            //=====================自定义异常=============================
            //int a = 1/0;
            //==========================================================
            //更新文章审核状态
            wmNews.setArticleId((long) responseResult.getData());
            updateWmNews(wmNews, WmNews.Status.PUBLISHED, "审核通过");
        }

    }

    /**
     * 1.从自媒体文章的内容中提取文本和图片
     * 2.提取文章的封面图片
     *
     * @param wmNews wm新闻
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //存储纯文本内容
        StringBuilder sb = new StringBuilder();
        List<String> imageUrls = new ArrayList<>();

        //1.从自媒体文章的内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if ("image".equals(map.get("type"))) {
                    imageUrls.add(map.get("value").toString());
                } else {
                    sb.append(map.get("value"));
                }
            }
        }
        //2.提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            imageUrls.addAll(Arrays.asList(split));
        }
        //3.处理标题中的文本
        sb.append(wmNews.getTitle());
        // 合
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("text", sb.toString());
        resultMap.put("images", imageUrls);
        return resultMap;
    }

    /**
     * 审核纯文本内容
     *
     * @param text   文本
     * @param wmNews wm新闻
     * @return boolean
     * @throws Exception 异常
     */
    private boolean handleTextScan(String text, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;
        if (StringUtils.isEmpty(text)) {
            return flag;
        }
        Map map = greenTextScan.greeTextScan(text);
        if ("block".equals(map.get("suggestion"))) {
            updateWmNews(wmNews, WmNews.Status.FAIL, "当前文章中存在违规内容");
            flag = Boolean.FALSE;
        } else if ("review".equals(map.get("suggestion"))) {
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH, "当前文章中存在不确定内容");
            flag = Boolean.FALSE;
        }
        return flag;
    }

    /**
     * 审核图片
     *
     * @param images 图片
     * @param wmNews wm新闻
     * @return boolean
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;
        if (null == images && images.size() == 0) {
            return flag;
        }
        List<byte[]> imageList = new ArrayList<>();
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        //下载图片 minIO
        for (String url : images) {
            byte[] bytes = fileStorageService.downLoadFile(url);

            //图片识别文字审核---begin-----
            //从byte[]转换为butteredImage
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage imageFile = ImageIO.read(in);
            //识别图片的文字
            String result = tess4jClient.doOCR(imageFile);
            //审核是否包含自管理的敏感词
            boolean status = handleSensitiveScan(result, wmNews);
            if (!status) {
                flag = Boolean.FALSE;
                return flag;
            }
            //图片识别文字审核---end-----

            imageList.add(bytes);
        }
        Map map = greenImageScan.imageScan(imageList);
        //审核图片
        if ("block".equals(map.get("suggestion"))) {
            updateWmNews(wmNews, WmNews.Status.FAIL, "当前图片中存在违规内容");
            flag = Boolean.FALSE;
        } else if ("review".equals(map.get("suggestion"))) {
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH, "当前图片中存在不确定内容");
            flag = Boolean.FALSE;
        }
        return flag;
    }

    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews wm新闻
     * @return {@link ResponseResult}
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDtoBuilder(wmNews, wmUserMapper, wmChannelMapper)
                .buildBeanCopy()
                .buildAuthor()
                .buildChannel()
                .buildBasic()
                .builder();
        //合
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    /**
     * 修改文章内容
     *
     * @param wmNews    wm新闻
     * @param reason    原因
     * @param published 发表
     */
    private void updateWmNews(WmNews wmNews, WmNews.Status published, String reason) {
        wmNews.setStatus(published.getCode());
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 自管理的敏感词审核
     *
     * @param content 内容
     * @param wmNews  wm新闻
     * @return boolean
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        Boolean flag = Boolean.TRUE;
        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper
                .selectList(Wrappers.<WmSensitive>lambdaQuery()
                        .select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives
                .stream()
                .map(WmSensitive::getSensitives)
                .collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, WmNews.Status.FAIL, "当前文章中存在违规内容" + map);
            flag = Boolean.FALSE;
        }

        return flag;
    }

}